DESCRIPTION
Selection Sort is an iterative and in-place sorting algorithm that divides the data structure in two sublists: the ordered one, and the unordered one. The algorithm loops for all the elements of the data structure and for every cycle picks the smallest element of the unordered sublist and adds it to the sorted sublist, progressively filling it.
It's a really simple and intuitive algorithm that does not require additional memory, but it's not really efficient on big data structures due to its quadratic time complexity.
COMPLEXITY
Average Case |
O(n 2) |
Best Case |
O(n 2) |
Worst Case |
O(n 2) |
Space complexity    |
O(1) |
IMPLEMENTATIONS
C++
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void SelectionSort(int arr[], int n)
{
int i, j, min;
for (i = 0; i < n - 1; i++)
{
min = i;
for (j = i + 1; j < n; j++)
{
if (arr[j] < arr[min])
{
min = j;
}
}
swap(&arr[min], &arr[i]);
}
}
Javascript
function SelectionSort(array)
{
for (let i = 0; i < array.length-1; i++)
{
let min = i;
for (let j = i + 1; j < array.length; j++)
{
if (array[min] > array[j])
{
min = j;
}
}
[array[i], array[min]] = [array[min], array[i]];
}
}